<template>
	<view>
		
		<view class="cu-bar">
			
			<view class="action">
				<text>{{$t('book.gy')}}{{DataList.length}}{{$t('user.ben')}}</text>
			</view>
			<view class="action">
				<text class="iconfont" @click="liecode" v-if="type">&#xe6e4;</text>
				<text class="iconfont" @click="liecode" v-else>&#xe6e5;</text>
					<text @click="editClick">管理书架</text>
			</view>
		</view>
		<view v-if="config.c_ad && adtype">
			<gr-ad :data="config" :type="adtype" :height="150" ref="adad"></gr-ad>
		</view>
		<view v-if="DataListlength>0">
			<view v-if="type==1" class="typelist">
				<uni-books-datalist :data="item" v-for="(item,index) in DataList" :key="index" @flags="wxad">
				</uni-books-datalist>
			</view>
			<view class="grid col-3 canui-list-box" v-else>
				<view class="padding-xs" v-for="(item,index) in DataList" :key="index" @click="wxad(item)">
					<image :src="item.img" class="radius"></image>
					<view class="tishi">
						<text>{{item.sum}}</text>
					</view>
					<view class="title">{{item.title}}</view>
				</view>
			</view>
		</view>

		<view class="iconfont booklist" v-else>
			<text style="font-size:60rpx;">&#xe605;</text>
			<text @click="cs">{{$t('book.all')}}</text>
		</view>
		<xy-dialog 
		    title="提示"
		    :show="isshow"
		    @cancelButton="clickCancel"
		    @confirmButton="clickConfirm"
			@close="clickclose">
		    <view style="padding: 0 30upx 30upx;">
		        <view>{{tname}}</view>
		        
		    </view>
		</xy-dialog>
		 <custom-tab-bar :currentTab="currentTab"></custom-tab-bar>
	</view>
</template>

<script>
	let rewardedVideoAd = null //激励视频
	// 在页面中定义激励视频广告
	let interstitialAd = null //激励调用
	import _tool from '@/util/tools.js';
	import _pc from '@/util/pc.js';
	import time from '@/util/getdateTime.js';
	// #ifdef  APP-PLUS
	import _sql from '@/util/sql.js';
	var testModule = uni.requireNativePlugin('Gr-AppUpdate-AppUpdateModule')
	// #endif
	import customTabBar from '@/components/customTabBar.vue';
	import xyDialog from '@/components/xy-dialog/xy-dialog.vue';
	export default {
		components: {
		    customTabBar,
			xyDialog
		  },
		data() {
			return {
				DataList: [],
				bookData:{},
				config: {},
				type: 1,
				thisTimeShow: false,
				DataListlength: 0,
				adtype:0,
				sum:0,
				tname:'',
				tt:0,
				ydus:0,
				zhong:0,
				adis:0,
				isad:0,
				adyujiazai:0,
				deviceType:'',
				tabBarList:[],
				currentTab:'/pages/bookshelf/index',
				isshow:false
			}
		},
		onLoad() {
			let _this = this;
			// #ifdef  APP-PLUS
			uni.getSystemInfo({
				success: function(res) {
					uni.setStorageSync('appVersionCode', res.appVersionCode)

					if (res.platform != 'ios') {
						_this.update(res)
					}
				}
			}); 
			// #endif
			this.GetBookList(1);
			this.type = uni.getStorageSync('listtype') ? uni.getStorageSync('listtype') : 1
		},
		onShareAppMessage(res) {
		    
		    return {
		      title: '阅读-免费小说畅读',
		      path: '/pages/bookshelf/index'
		    }
		},
		onShareTimeline(){
			return {
			  title: '阅读-免费小说畅读',
			  query: '/pages/bookshelf/index',
			  imageUrl:'https://bookcover.yuewen.com/qdbimg/349573/1031777108/150.jpg'
			}
		},
		onHide() {
			
			// #ifdef  MP
			if (this.zhong) {
				uni.setStorageSync('adis',1)
				console.log('我点击了广告',uni.getStorageSync('adis'))
				this.adis = 1
				this.zengjia()
			}
			// #endif 
		},
		onUnload() {
		// #ifdef  MP
		if (this.zhong) {
			uni.setStorageSync('adis',1)
			this.adis = 1
		}
		// #endif 
		      // 页面关闭后销毁实例
		if(this.interstitialAd){
		      this.interstitialAd.destroy()
		}
		},
		onShow() {
			let _this=this
			uni.$emit('ad_time')
		
			// #ifdef  MP
			//uni.setStorageSync('adis',0)
			// #endif 
			_pc.system()
		
			// #ifdef MP || H5
			
			this.get(this.Httpus+'/index.php?s=Home-Ad-config')
			// 在页面onLoad回调事件中创建插屏广告实例
		
			// #endif 
		
			// #ifdef  APP-PLUS
		
			_sql.openDB()
			// #endif
			//console.log(time.timej(800,0))
			this.GetBookList(0); 
		},
		methods: {
			jlad() {
				let _this = this;
				if (wx.createRewardedVideoAd) {
					rewardedVideoAd = wx.createRewardedVideoAd({
						adUnitId: _this.config.wx_ad_jl
					})
					rewardedVideoAd.onLoad(() => {
						console.log('onLoad event emit')
						_this.adis = 0
						_this.adyujiazai = 0
					})
					rewardedVideoAd.onError((err) => {
						console.log('onError event emit', err)
						_this.adis = 0
						_this.adyujiazai = 0
						uni.showToast({
							icon: 'none',
							title: '当前未获取到广告资源，请稍后再试',
							duration: 2000
						});
			
					})
					rewardedVideoAd.onClose((res) => {
						// 用户点击了【关闭广告】按钮
					
			console.log('正常播放结束，可以下发游戏奖励',res,res.isEnded)
						if (res && res.isEnded) {
							_this.adyujiazai++;
							_this.ydus = 1
							_this.zhong = 1;
							_this.zengjia()
							setTimeout(()=>{
								uni.setStorageSync('adis',0)
								_this.readClick()	
							},1500)
							// 正常播放结束，可以下发游戏奖励
						} else {
							_this.adis = 0
							_this.adyujiazai = 0;
							if (_this.adis && _this.zhong) {
								if(_this.zhong!=2){
								uni.showToast({
									icon: 'none',
									title: '中途关闭了广告，无法为您获取权限！',
									duration: 2000
								});
								}
			
							} else {
								if(_this.zhong!=2){
								uni.showToast({
									icon: 'none',
									title: '中途关闭了广告，无法为您获取权限!',
									duration: 2000
								});
							}
							}
							this.adyujiazai = 0
							uni.setStorageSync('adis',0)
							// 播放中途退出，不下发游戏奖励
							console.log('播放中途退出，不下发游戏奖励')
							//_this.readClick()
						}
					}) 
			
				}
			
			
				// 在页面onLoad回调事件中创建插屏广告实例
				if (wx.createInterstitialAd) {
					interstitialAd = wx.createInterstitialAd({
						adUnitId: this.config.wx_ad_ys_cp
					})
					interstitialAd.onLoad(() => {})
					interstitialAd.onError((err) => {})
					interstitialAd.onClose(() => {})
				}
			},
			clickCancel(e){
				this.isshow=!this.isshow
				uni.setStorageSync('urlxxa', this.config.book_source_list);
				
				uni.navigateTo({
					url: '/pages/about/url' 
				})
				console.log('点击了1',e)
			},
			clickclose(){
				this.isshow=!this.isshow
			},
			clickConfirm(e){
				this.isshow=false
				
				
				// #ifdef  MP
				
				setTimeout(res => {

					rewardedVideoAd.show().then(() => {
						
						console.log('激励视频 广告显示')
					}).catch(err => {
						uni.showToast({
							icon: 'none',
							title: '当前未获取到广告资源，请稍后再试',
							duration: 2000
						});
					})
				}, 1000)
			// #endif 
				
			},
			wxad(data) {
				var _this = this;
				this.bookData=data;
				console.log(time.dtime())
				let tt = time.getInervalHour(time.dtime(), uni.getStorageSync('config_time'))
				if (tt != '0分') {
					_this.readClick()
					
					return false
				} 
				console.log('this.config.task_wx_status_j',this.config.task_wx_status_j)
				if(this.config.task_wx_status_j==0){
					_this.readClick()
					
					return false
				}
				let sum = 0;
				let urls = [];
				for (let i = 0; i < 100 / parseInt(this.config.task_wx_statussj); i++) {
					urls.push(i + 1);
				}
				var element = urls[Math.floor((Math.random() * urls.length))]
				this.isshow=!this.isshow
				if (element === urls.length) {
					
					this.zhong = 1;
			
				this.tname=this.tname=this.config.task_wx_q_name
			
				} else {
		
			this.tname=this.config.task_wx_q_name
			this.zhong = 0;
			console.log('未启动强点', this.zhong)
			setTimeout(res => {
			
				rewardedVideoAd.show().then(() => console.log('激励视频 广告显示'))
			}, 1000)
				}
			
			
			
			
				
			},
			zengjia() {
				console.log('this.adyujiazai', this.adyujiazai)
				if (this.adyujiazai > 2) {
					console.log('this.进去了', this.adyujiazai)
					this.isad = 0
					
					return;
			
				}
				this.config = uni.getStorageSync('config');
				this.tt = parseInt(uni.getStorageSync('config_time'));
				console.log('this.tt',this.tt,this.adis,this.zhong,this.ydus)
				this.adis=this.adis?this.adis:uni.getStorageSync('adis');
				if (this.adis && this.zhong == 1 && this.ydus == 1) {
					uni.setStorageSync('adis',0)
					let times = this.tt ? (this.tt + parseInt(this.config.task_wx_status_j_time)) : parseInt(this.config
						.task_wx_status_j_time)
			
					if (this.tt < time.dtime()) {
						this.tt = 0
					}
					let st = this.tt ? time.timej(times, this.tt) : time.timej(times, 0)
					uni.setStorageSync('config_time', st);
					this.zhong = 0
					this.adis = 0
					this.isad = 0
					uni.setStorageSync('adis',0)
					this.config.task_wx_status_j = 0;
					this.$forceUpdate()
				
					uni.showToast({
						icon: 'none',
						title: '成功获取24小时畅读权限！',
						duration: 2000
					});
					uni.$emit('ad_time',{msg:'页面更新'})
				}
				if (this.zhong == 2) {
					console.log('中标判断----xxx---', this.zhong)
					let times = this.tt ? (this.tt + parseInt(this.config.task_wx_status_b_time)) : parseInt(this.config
						.task_wx_status_b_time)
			
					if (this.tt < time.dtime()) {
						this.tt = 0
					}
					let st = this.tt ? time.timej(times, this.tt) : time.timej(times, 0)
					uni.setStorageSync('config_time', st);
					this.zhong = 0
					this.adis = 0
					this.isad = 0
					this.config.task_wx_status_j = 0;
					this.$forceUpdate()
					uni.showToast({
						icon: 'none',
						title: '成功获取24小时畅读权限！',
						duration: 2000
					});
				}
			
				if (this.adis == 0 && this.zhong == 1) {
					this.zhong = 0
					this.adis = 0
					uni.showToast({
						icon: 'none',
						title: '未点击绿色按钮体验，24小时畅读权限获取失败！',
						duration: 4000
					});
				}
			
			
			},
			createInterstitialAd() {
				interstitialAd = this.interstitialAd = uni.createInterstitialAd({
					'adpid': this.config.app_ad_ys_cp
				});
				interstitialAd.onLoad(() => {
					this.loading = false;
					console.log("插屏 广告加载成功");
				});
				interstitialAd.onClose(() => {
					// 用户点击了关闭或返回键(仅Android有返回键)
					console.log("插屏 广告关闭");
				});
				interstitialAd.onError((err) => {
					this.loading = false;
					console.log("插屏 广告加载失败");
				});
			
				// 广告实例创建成功后默认会执行一次 load，加载广告数据
				// 如果界面有 "显示广告" 按钮，需要先禁用掉，防止用户点击，等待广告数据加载成功后在放开
				this.loading = true;
			},
			showInterstitialAd() {
				// 调用 interstitialAd.show()，如果数据正在加载中不会显示广告，加载成功后才显示
				// 在数据没有加载成功时，需要防止用户频繁点击显示广告
				if (this.loading == true) {
					return
				}
				this.loading = true;
				this.interstitialAd.show().then(() => {
					this.loading = false;
				});
			},
			get(url) {

				uni.setStorageSync('shuyuan1', null)
				let _this=this;
				this.zaiApi({
					url: url,
				}).then((res) => {
					if (wx.createInterstitialAd && res.wx_ad_ys_cp && parseInt(res.task_wx_status_j)) {
						interstitialAd = wx.createInterstitialAd({
							adUnitId: res.wx_ad_ys_cp
						})
						interstitialAd.onLoad(() => {})
						interstitialAd.onError((err) => {})
						interstitialAd.onClose(() => {})
					}
					this.adtype=res.ad_status
					if (res.book_source_book) {
						
						_this.zaiApi({
							url: res.book_source_book,
						}).then(ress => {
							
							
							uni.setStorageSync('shuyuan1', ress)
						}).catch(err => {
							
						});
						_this.zaiApi({
							url: res.book_source_yuan,
						}).then(ress => {
						
							uni.setStorageSync('shukudata', ress)
						}).catch(err => {
							
						});
					}
					_this.config = res;
					_this.jlad()
					uni.setStorageSync('config', res);
					// if (_this.config.ad_status) {
					// 	setTimeout(() => {
					// 		//修改子组件的内容
					// 		this.$nextTick(() => {
					// 			_this.$refs.adad.update_ad()
					// 		})
					// 	}, 1000);
					// }
				}).catch(err => {
					
					
				
				});
			},
			liecode() {
				uni.setStorageSync('listtype', !this.type);
				this.type = !this.type
				// this.$forceUpdate() 
			},
			cs() {
				this.zaiApi({
					url: '/',
				}).then((res) => {
					console.log(res)
				})

			},
			msg() {
				uni.showLoading({
					title: this.$t('system.app'),
					mask: true
				});
			},
			update(config) {
				let _this = this;
				let data = uni.getStorageSync('data_url') ? uni.getStorageSync('data_url') :
					'http://ad.xybook.xyz/index.php?s=Home-Ad-config';
					
				this.zaiApi({
					url: data,
				}).then((res) => {
				

					if (config.appVersionCode != res.app_version) {

						_this.checkUpdate(res)
					}
					_this.config = res;
					_this.adtype=res.ad_status
					uni.setStorageSync('config', res);
					if (res.app_status == 0) {
						_this.msg();
					}
					if (_this.config.ad_status && _this.config.ad_status) { 
						this.adtype=res.ad_status
						setTimeout(() => {
							//修改子组件的内容
							this.$nextTick(() => {
								_this.$refs.adad.update_ad()
							})
						}, 1000);
					}
				}).catch(err => {  
					uni.setStorageSync('data_url', 'http://ad.xybook.xyz/index.php?s=Home-Ad-config')
					setTimeout(() => {
						// this.update()
					}, 10000);
					//  this.zaiApi({
					//    url: 'https://gitee.com/gxlcms/ruanjian',
					//  }).then((res) => {
					//    _tool.GetInterceptTheSpecifiedString(res,'</h3>$</p>').then((xx) => {

					//     })
					//  }).catch(err=>{
					//  });
				});

			},
			checkUpdate(data) {
				testModule.update({
					url: data.app_down, //下载链接
					title: this.$t('system.update'), //标题
					content: data.app_keywords, //更新内容
					isForce: data.app_is_status, //是否强制更新
					//推荐更新可以使用参数
					thisTimeShow: this.thisTimeShow, //本次是否显示更新弹窗
					isAlwaysShow: true, //推荐更新是否每次都提示
					isAlwaysShowDownLoadDialog: true, //推荐更新下载时是否显示下载进度弹窗
				})
			},
			GetBookList(id) {
				let _this = this;
				_tool.GetBookListData().then((res) => {
					
					if (res == "" || res == null || res == undefined) {
						this.DataList = []
					} else {
						this.DataList = res;
					}
					
					this.DataListlength = this.DataList.length;
					
					this.DataList.forEach((value, index) => {
						
						if (_this.num(value)) {
							value.sum = _this.listcount(value.list,value.id) - _this.num(value);
							value.ylist = _this.listname(value.list,value.id,_this.num(value))
						} else {
							
							value.sum = _this.listcount(value.list,value.id);
							value.ylist =_this.listname(value.list,value.id,0);
						}
						value.sumlist = _this.listname(value.list,value.id,_this.listcount(value.list,value.id)-1)
						_this.DataList[index] = value
						_this.GetBookDetails(value.id,value.data,index)
					})
					if (id) {
						this.shuup()
					}
				});
			},
			async shuup() {
				let _this = this;
				for (var i = 0; i < _this.DataList.length; i++) {
					await _this.GetBookDetails(_this.DataList[i].id, _this.DataList[i].data, i)
				}
			},
			async GetBookDetails(id, data, index) {
				return new Promise((resolve) => {
					let url = data.source.rand_url.replace("{{key}}", id);
					setTimeout(async () => {
						this.zaiApi({
							url: url,
						}).then(async (res) => {
							await this.GetDetailsData(res, data, id, index)
						});
						resolve()
					}, 2000)
				});
			},
			async GetDetailsData(Book, data, id, index) {
				return new Promise((resolve) => {
					let _this = this;
					_tool.DetailsData(Book, data.source, id).then((res) => {
						_this.DataList[index].list = res.list
						uni.setStorageSync('bookshelf_list', _this.DataList)
						// console.log(res.list)
					});
					resolve()
				});
			},
			num(item) {
				let data = uni.getStorageSync('history') || []
				
				let count = 0
				data.forEach((value) => {
					if (value.bookId === item.id) {
						count = value.chapterIndex
					}
				})
				
				return count

			},
			listname(item,id,index){
				let length=item.length
				
				if(length<=0){
					let size=uni.getStorageSync('book_list1'+id)+uni.getStorageSync('book_list2'+id) ?JSON.parse(uni.getStorageSync('book_list1'+id)+uni.getStorageSync('book_list2'+id)) : []
					
					return size.length?size[index].name:''
					
				}else{
					
				  return  item[index].name 	 
				}
			},
			listcount(item,id) {
				let length=item.length
				if(length<=0){
					let size=uni.getStorageSync('book_list1'+id)+uni.getStorageSync('book_list2'+id) ?JSON.parse(uni.getStorageSync('book_list1'+id)+uni.getStorageSync('book_list2'+id)) : []
					
					return size.length
					
				}else{
					
				  return length	 
				}
				console.log('3333333',item,id)
			
			},
			editClick() {
				uni.navigateTo({
					url: '/pages/bookshelf/edit'
				})
			},
			readClick() {
				
				uni.setStorageSync('BookReadData', this.bookData);
				try {

					uni.navigateTo({
						url: '/pages/bookshelf/read'
					})
				} catch (e) {
					uni.showToast({
						title: this.$t('book.sjyc'),
						icon: 'none'
					});
				}
			}
		}
	}
</script>

<style lang="less">
	.canui-list-box {
		image {
			height: 330rpx;
		}
	}

	.typelist {
		padding: 20rpx;
	}

	.col-3 {
		.radius {
			height: 320rpx;
			background-image: url('@/static/bakerBook.png');
			background-size: 100% 100%;
			background-position: 50% 50%;
			background-repeat: no-repeat;
		}

		.title {
			text-align: center;
		}
	}

	.tishi {
		background: #999999c7;
		height: 50rpx;
		position: relative;
		margin-top: -60rpx;
		font-size: 26rpx;
		line-height: 50rpx;
		padding-left: 5rpx;
		color: #fff;
		text-align: center;
	}

	.booklist {
		display: block;
		text-align: center;
		margin-top: 300rpx;
		color: #555555;
		font-size: 30rpx;
	}
	.iconfont {
	    font-family: "iconfont" !important;
	    font-size: 14px;
	    font-style: normal;
	    -webkit-font-smoothing: antialiased;
	    -moz-osx-font-smoothing: grayscale;
	}
</style>
